package boot.spring.controller;

import boot.spring.po.Post;
import boot.spring.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PostController {

    @Autowired
    private PostService postService;
    // 处理帖子详情页面请求的方法
    @GetMapping("/post/detail")
    public String getPostDetail(@RequestParam("id") int postId, Model model) {
        try {
            // 调用 PostService 的方法获取帖子详情
            Post post = postService.getPostById(postId);
            if (post != null) {
                // 将帖子信息添加到模型中
                model.addAttribute("post", post);
                return "postDetail"; // 返回对应的 Thymeleaf 模板名称
            } else {
                // 若帖子不存在，可以返回错误页面或者重定向
                return "error";
            }
        } catch (Exception e) {
            // 处理异常，返回错误页面
            return "error";
        }
    }

    @RequestMapping(value="/index",method=RequestMethod.GET)
    public String index(HttpSession httpSession){

            return "index";

    }



    @GetMapping("/api/posts")
    @ResponseBody
    public Map<String, Object> getPosts(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> result = new HashMap<>();
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Post> postPage = postService.getPostsByPage(pageable);
        result.put("posts", postPage.getContent());
        return result;
    }

    @PostMapping("/api/posts")
    @ResponseBody
    public ResponseEntity<String> createPost(@RequestBody Post post) {

        // 从请求体中提取数据

        try {
            // 这里假设你有一个方法可以创建新的 Post 对象并保存到数据库
            // 由于不知道 PostService 的具体实现，这里只是示例调用

            postService.savePost(post);

            return new ResponseEntity<>("帖子创建成功", HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>("帖子创建失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("/api/posts/{postId}")
    @ResponseBody
    public ResponseEntity<String> deletePost(@PathVariable int postId) {
        try {
            // 调用 PostService 的删除方法
            postService.deletePost(postId);
            return new ResponseEntity<>("帖子删除成功", HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("帖子删除失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}